﻿using Minecraft.BLL;
using Minecraft.BLL.mysql;
using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Config.Csv.CsvCom;
using Minecraft.Config.ipConst;
using Minecraft.Model;
using Minecraft.Model.Dropinfo;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Minecraft.ServerHall.Cmd
{
	public class DropinfoResourceCollect : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Dropinfo_DropinfoResourceCollect;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<DropinfoResourceCollectReq>(session);
			if (req == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：请求实体为空）" });
				return;
			}
			if (!session.minecraftSessionInfo.IsLogin)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：未登录）" });
				return;
			}
			if (req.resourceItemId.IsNullOrWhiteSpace())
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：resourceItemId参数为空）" });
				return;
			}
			Mod_Drawing mod_Drawing = CsvConfig.GetMod_DrawingInfoById(req.resourceItemId);
			if (!session.GetDrawingResourceTypeIdList().Any(m => m == mod_Drawing.Type_Convert))
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：为【{req.resourceItemId}】的itemId不属于资源采集的范畴）" });
				return;
			}

			Mod_Drop mod_Drop = CsvConfig.GetMod_DropInfoById(mod_Drawing.Drop);
			if (mod_Drop == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：掉落配置表中id为【{mod_Drawing.Drop}】的掉落信息为空）" });
				return;
			}

			List<DropinfoDropResourceInfo> dropinfoDropResourceInfoList = session.GetDropinfoDropRandomResourceInfoList(mod_Drop.Id);

			//经验特殊处理
			int dropExp = 0;
			var expDropResourceInfo = dropinfoDropResourceInfoList.FirstOrDefault(m => m.GoodsItemId == MinecraftConfig.ExperienceItemId);
			if (expDropResourceInfo != null)
			{
				var expItemInfo = CsvConfig.GetMod_ItemsInfoById(expDropResourceInfo.GoodsItemId);
				if (expItemInfo == null)
				{
					session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：物品表中 expItemInfo id为【{expDropResourceInfo.GoodsItemId}】 经验信息为空）" });
					return;
				}
				var behaviorInfo = CsvConfig.GetMod_BehaviorInfoById(expItemInfo.Behavior_id);
				if (behaviorInfo == null)
				{
					session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：行为表中 behaviorInfo id为 【{expItemInfo.Behavior_id}】 信息为空）" });
					return;
				}
				Match match = Regex.Match(behaviorInfo.Behavior, @"AlterAttribute\((\d+)#(\d+)\)");
				if (!match.Success)
				{
					session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：行为表中 behaviorInfo id为 【{expItemInfo.Behavior_id}】正则匹配不成功）" });
					return;
				}
				EnumAttribute enumAttribute = (EnumAttribute)int.Parse(match.Groups[1].Value);
				int expValue = int.Parse(match.Groups[2].Value);
				if (enumAttribute != EnumAttribute.CurExp)
				{
					session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：行为表中 behaviorInfo id为 【{expItemInfo.Behavior_id}】正则匹配 的第一个 group值 为 【{match.Groups[1].Value}】，并不是【{EnumAttribute.CurExp.ToString()}】）" });
					return;
				}
				//直接加经验
				dropExp = expDropResourceInfo.Num * expValue;
				session.minecraftSessionInfo.player.Exp += dropExp;
				dropinfoDropResourceInfoList.RemoveAll(m => m.GoodsItemId == expDropResourceInfo.GoodsItemId);
			}
			var map = session.minecraftSessionInfo.map;
			if (map.isBig_Convert)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：玩家正处于大地图界面中，不允许操作）" });
				return;
			}
			var timeNow = DateTimeOffset.Now;
			//计入掉落数据表
			DropinfoModel dropinfoModel = new DropinfoModel
			{
				DropId = session.GetNewDropInfoId(),
				PlayerId = session.minecraftSessionInfo.player.PlayerId,
				MapId = map.SourceMapId,
				DropTime = timeNow,
				DropItemIdAndNum = string.Join("|", dropinfoDropResourceInfoList.ToList().ConvertAll(info =>
				{
					return string.Join("#", info.GoodsItemId, info.Num);
				}).ToArray()),
			};
			session.minecraftSessionInfo.dropinfoList.Add(dropinfoModel);
			var resp = new DropinfoResourceCollectResp
			{
				DropId = dropinfoModel.DropId,
				dropinfoDropResourceInfoList = dropinfoDropResourceInfoList,
				dropExp = dropExp,
				curExp = session.minecraftSessionInfo.player.Exp,
				resourceId = req.resourceId,
				keyValuePair = new KeyValuePair<int, int>(3, 4),
			};
			session.Send(defCommand, req, resp);
		}
	}
}
